<?php

/**
 * 账号设置
 * @author shaun
 */

namespace Admin\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;
use Member\Table\MemberTable;
use Member\Model\MemberModel;
use Zend\Form\Form;
use Utility\Log\Logger;

class AccountController extends AbstractActionController {

    private $dir;
    private $small;

    public function __construct() {
        $this->dir = $_SERVER['DOCUMENT_ROOT'] . "/upload/image/admin/original/";
        $this->small = $_SERVER['DOCUMENT_ROOT'] . "/upload/image/admin/thumbnail/";
    }

    public function indexAction() {
        $this->layout()->class = 'account';
        $admin = new MemberModel();
        $data = $admin->SelectAll()->toArray();

        return new ViewModel(array("data" => $data[0]));
    }

    //添加
    public function addAction() {

    }

    //修改
    public function editAction() {
        $request = $this->getRequest();
        if ($request->isPost()) {
            $admin = new MemberModel();
            $post = $request->getPost();
            if ($_FILES['file']['name']) {
                $fileData = $this->Files($_FILES);
                if ($fileData['result']) {
                    $post['image'] = $fileData['image'];
                    $adminData = $admin->SelectByCond(array("id" => $post['id']))->toArray();
                    if (is_file($this->dir . $adminData[0]['image'])) {
                        @unlink($this->dir . $adminData[0]['image']);
                    }
                    if (is_file($this->small . $adminData[0]['image'])) {
                        @unlink($this->small . $adminData[0]['image']);
                    }
                } else {
                    return $this->redirect()->toRoute('admin/child', array('controller' => 'ShowMessage', 'action' => 'failure', 'par' => 'Account', 'msg' => $fileData['msg']));
                }
            }

            $form = new Form(); // 实例 表单模型, 用来效验提交的数据
            $MemberModel = new MemberModel();
            $form->setInputFilter($MemberModel->getInputFilter()); //
            $form->setData($post); // $request->getPost() 获取 提交的数据对象 写入 Form
            if ($form->isValid()) {
                $Fdata = $form->getData();
                $MemberModel->exchangeArray($Fdata);
                if ($MemberModel->Insert()) {
                    return $this->redirect()->toRoute('admin/child', array('controller' => 'ShowMessage', 'action' => 'success', 'par' => 'Account'));
                } else {
                    return $this->redirect()->toRoute('admin/child', array('controller' => 'ShowMessage', 'action' => 'failure', 'par' => 'Account'));
                }
            } else {
                // 提交的数据不正确
                $array = array();
                foreach ($form->getInputFilter()->getInvalidInput() as $value) {
                    //循环出来 写入日志 及 组成 JSON返回到页面
                    Logger::getLogger()->debug(__CLASS__ . "::" . __FUNCTION__ . " [" . $value->getName() . "}" . implode('', $value->getMessages()));
                    array_push($array, $value->getName());
                }
                return $this->redirect()->toRoute('admin/child', array('controller' => 'ShowMessage', 'action' => 'failure', 'par' => 'Account'));
            }
        } else {
            return $this->redirect()->toRoute('admin/child', array('controller' => 'ShowMessage', 'action' => 'failure', 'par' => 'Account'));
        }
    }

    //处理上传头像
    private function Files($file) {
        $suffix = substr(strrchr($file['file']['name'], '.'), 1);
        $size = (int) ($file["file"]["size"]);
        // 判断格式
        if ($suffix != "jpg" && $suffix != "gif" && $suffix != "png") {
            return array("result" => false, 'msg' => 'IMAGE_FORMAT_ERROR');
        }
        // 判断大小 不超过 2MB
        if ($size > 2 * 1024 * 1024) {
            return array("result" => false, 'msg' => 'IMAGE_EXCEED_THE_SIZE');
        }
        //创建文件夹
        $dir = $this->dir;
        if (!is_dir($dir)) {
            mkdir($dir, 0777);
        }
        $imgName = md5(date("YmdHis"));
        $imgName = $imgName . "." . $suffix;
        move_uploaded_file($file["file"]["tmp_name"], $dir . $imgName);
        $width = 230;
        $height = 230;
        $small = $this->small;
        if (!is_dir($small)) {
            mkdir($small, 0777);
        }
        $this->img_create_small($dir . $imgName, $width, $height, $small . $imgName);
        return array("result" => true, 'image' => $imgName);
    }

    //生成缩略图
    private function img_create_small($big_img, $width, $height, $small_img) {//原始大图地址，缩略图宽度，高度，缩略图地址
        $imgage = getimagesize($big_img); //得到原始大图片
        switch ($imgage[2]) { // 图像类型判断
            case 1:
                $im = imagecreatefromgif($big_img);
                break;
            case 2:
                $im = imagecreatefromjpeg($big_img);
                break;
            case 3:
                $im = imagecreatefrompng($big_img);
                break;
        }
        $src_W = $imgage[0]; //获取大图片宽度
        $src_H = $imgage[1]; //获取大图片高度
        $tn = imagecreatetruecolor($width, $height); //创建缩略图
        imagecopyresampled($tn, $im, 0, 0, 0, 0, $width, $height, $src_W, $src_H); //复制图像并改变大小
        imagejpeg($tn, $small_img); //输出图像
    }

}
